<template>
  <BasicModal
    title="导出列配置"
    :width="700"
    v-bind="$attrs"
    @register="registerModel"
    @ok="handleSubmit"
    :useWrapper="true"
    destroyOnClose
  >
    <div>
      <div>
        <a-checkbox
          v-model:checked="state.checkAll"
          :indeterminate="state.indeterminate"
          @change="onCheckAllChange"
        >
          全选
        </a-checkbox>
      </div>
      <a-divider />
      <a-checkbox-group
        style="width: 100%"
        v-model:value="state.checkedList"
        :options="optionsRef"
      />
    </div>
  </BasicModal>
</template>
<script setup lang="ts">
  import BasicModal from '@/components/Modal/src/BasicModal.vue';
  import { useModalInner } from '@/components/Modal';
  import {
    CheckboxGroup as ACheckboxGroup,
    Checkbox as ACheckbox,
    Divider as ADivider,
  } from 'ant-design-vue';

  import { reactive, ref, toRaw, watch } from 'vue';
  import { useDpColumnsStore } from '@/store/modules/dp_columns';
  import { map } from 'lodash-es';
  import { useMessage } from '@/hooks/web/useMessage';
  import { checkcolumns } from '@/views/dp_platform/qiangua.api';

  const emit = defineEmits(['success', 'register']);
  const optionsRef = ref<any>([]);

  const state = reactive({
    indeterminate: false,
    checkAll: false,
    checkedList: [],
  });
  const pkid = ref();
  const onCheckAllChange = (e: any) => {
    Object.assign(state, {
      checkedList: e.target.checked ? map(optionsRef.value, (item) => item.value) : [],
      indeterminate: false,
    });
  };
  watch(
    () => state.checkedList,
    (val) => {
      state.indeterminate = !!val.length && val.length < optionsRef.value.length;
      state.checkAll = val.length === optionsRef.value.length;
    },
  );
  var dpColumnsStore = useDpColumnsStore();
  const [registerModel, { closeModal, changeOkLoading }] = useModalInner(async (data) => {
    state.indeterminate = false;
    state.checkAll = false;
    const { record } = data;
    pkid.value = record['id'];
    state.checkedList = record['columns'] ?? [];
    changeOkLoading(false);
    if (record['type'] == 1) {
      optionsRef.value = dpColumnsStore.getQianguaColumns;
    } else {
      optionsRef.value = dpColumnsStore.getPgyColumns;
    }
  });
  const { createMessage } = useMessage();
  const handleSubmit = async () => {
    if (state.checkedList.length == 0) {
      createMessage.warn('请选择要导出的列');
      return;
    }
    changeOkLoading(true);
    await checkcolumns({ id: pkid.value, columns: toRaw(state.checkedList) });
    closeModal();
    emit('success');
  };
</script>
<style lang="less" scoped>
  ::v-deep(.ant-divider-horizontal) {
    margin: 14px 0;
  }
  ::v-deep(.ant-checkbox-wrapper) {
    width: 30%;
    margin-top: 5px;
  }
</style>
